package com.zhang.novel.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.zhang.novel.core.config.OssProperties;
import com.zhang.novel.core.utils.Constants;
import com.zhang.novel.core.utils.FileUtil;
import com.zhang.novel.service.FileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.io.File;

@Service
@Slf4j
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "pic.save",name = "storage",havingValue = "OSS")
public class OssFileServiceImpl implements FileService {

    private final OssProperties ossProperties;

    @Override
    public String transPic(String picSrc, String picSavePath) {
        File file;

        String filePath = FileUtil.network2Local(picSrc,picSavePath,Constants.LOCAL_PIC_PREFIX);

        if(filePath.contains(Constants.LOCAL_PIC_PREFIX)){
            file=new File(picSavePath+filePath);
        }else {
            // 默认图片不存储
            return filePath;
        }

//        filePath=filePath.replaceFirst(picSavePath,"");

        filePath=filePath.startsWith("/")?filePath.replaceFirst("/",""):filePath;

        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getKeyId(), ossProperties.getKeySecret());
        try{
            if(!ossClient.doesBucketExist(ossProperties.getBucketName())){
                // 容器不存在，就创建
                ossClient.createBucket(ossProperties.getBucketName());
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(ossProperties.getBucketName());
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }

            // 上传文件
            PutObjectResult result = ossClient.putObject(ossProperties.getBucketName(), filePath, file);

            // 设置图片的权限
            ossClient.setBucketAcl(ossProperties.getBucketName(),CannedAccessControlList.PublicRead);

            if(null != result){
                return  ossProperties.getWebUrl()+"/"+filePath;
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }finally {
            // 关闭
            ossClient.shutdown();
            // 删除
            file.delete();
        }
        return "images/default.gif";
    }
}
